package com.shop.cereshop.app.dl.logic.utils.YunUtil;


import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import com.alibaba.fastjson.JSONObject;

/**
 * @program: dlshop
 * 描述：
 * @author: 我好帅
 * @create: 2021-07-30 11:32
 **/
public class checkContent {

    static String appid = "";
    static String appkey = "";
    static String url = "";

    static String signature;
    static String authorization1 = "OPEN-FORM-PARAM";

    public static void main(String[] args) throws Exception {

        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String s = UUID.randomUUID().toString();

        Base64 base64 = new Base64();

        JSONObject body = new JSONObject();
        body.put("requestTimestamp", format1.format(date).toString());   // 商户号
        body.put("merOrderId", format2.format(date) + "1211456");
        body.put("mid", ""); // 商户号
        body.put("tid", ""); // 终端号
        body.put("instMid", "H5DEFAULT");
        body.put("totalAmount", "1");
        body.put("inAcctNo", base64.encodeToString("6217002980104658468".getBytes()));
        body.put("inAcctName", base64.encodeToString("建设".getBytes()));
        body.put("chnlType", "H5");
//		body.put("","");


        // 2. 获取认证报文，timestamp为当前日期，老旧日期无法请求成功
        String authorization = getAuthorization(appid, appkey, format.format(date).toString(), format2.format(date) + s,
                body.toString());
        System.out.println("authorization:\n" + authorization);


        String newUrl = url + "?authorization=" + authorization1 + "&appId=" + appid + "&timestamp=" + format.format(date).toString() + "&nonce=" + format2.format(date) + s + "&content=" + URLEncoder.encode(body.toString(), "UTF-8") + "&signature=" + URLEncoder.encode(signature, "UTF-8");
        System.out.println(newUrl);
    }

    /**
     * 发送http请求
     *
     * @param url           请求url
     * @param authorization 认证报文
     * @param reqBody       请求体
     * @return response
     */
    static String request(String url, String authorization, String reqBody) {
        String response = "";
        PrintWriter out = null;
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            HttpURLConnection httpUrlConnection = (HttpURLConnection) conn;
            httpUrlConnection.setRequestProperty("Content-Type", "application/json");
            httpUrlConnection.setRequestProperty("authorization", authorization);
            httpUrlConnection.setDoOutput(true);
            httpUrlConnection.setDoInput(true);
            out = new PrintWriter(httpUrlConnection.getOutputStream());
            out.write(reqBody);
            out.flush();
            httpUrlConnection.connect();
            in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                response += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return response;
    }

    /**
     * 获取签名头
     *
     * @param appid
     * @param appkey
     * @param timestamp 格式:"yyyyMMddHHmmss"
     * @param nonce     随机字符串，
     * @param body      请求体
     * @return authorization 认证报文
     * @throws Exception
     */
    static String getAuthorization(String appid, String appkey, String timestamp, String nonce, String body)
            throws Exception {
        byte[] data = body.getBytes("utf-8");
        InputStream is = new ByteArrayInputStream(data);
        String testSH = DigestUtils.sha256Hex(is);
        String s1 = appid + timestamp + nonce + testSH;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(appkey.getBytes("utf-8"), "HmacSHA256"));
        byte[] localSignature = mac.doFinal(s1.getBytes("utf-8"));
        String localSignatureStr = Base64.encodeBase64String(localSignature);
        signature = localSignatureStr;
        return "OPEN-BODY-SIG AppId=" + "\"" + appid + "\"" + ", Timestamp=" + "\"" + timestamp + "\"" + ", Nonce="
                + "\"" + nonce + "\"" + ", Signature=" + "\"" + localSignatureStr + "\"";
    }

}
